/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By zhanglin
* 注意：
* 本软件为zhanglin开发研制
 */
package model

import (
	"shop/global"
	"time"
)

type IDept interface {
	InsertDept() (int64, error)
	DeleteDept(id int64) error
	UpdateDept() error
	FindDeptList() (interface{}, error)
	SplitPageDeptList(pageIndex int64, pageSize int64) (interface{}, error)
}

/**
	Dept实体对象
 **/
type Dept struct {
	Id int64 `json:"id" gorm:"primary_key"` //ID

	Name string `json:"name"` //名称

	Pid int64 `json:"pid"` //上级部门

	Enabled bool `json:"enabled"` //状态

	CreateTime time.Time `json:"create_time"` //创建日期
}

func (vo *Dept) InsertDept() (int64, error) {
	table := global.GDB.Table("dept")
	if err := table.Create(&vo).Error; err != nil {
		return 0, err
	}

	return vo.Id, nil
}

func (vo *Dept) DeleteDept(id int64) error {
	table := global.GDB.Table("dept")
	table = table.Where("id = ?", id)
	if err := table.Delete(Dept{}).Error; err != nil {
		return err
	}
	return nil
}

func (vo *Dept) UpdateDept() error {

	table := global.GDB.Table("dept")
	table = table.Where("id = ?", vo.Id)
	if err := table.Updates(map[string]interface{}{
		"id": vo.Id, "name": vo.Name, "pid": vo.Pid, "enabled": vo.Enabled, "create_time": vo.CreateTime}).Error; err != nil {
		return err
	}
	return nil
}

func (vo *Dept) FindDeptList() ([]Dept, error) {
	var lists []Dept
	table := global.GDB.Table("dept")
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}
	return lists, nil
}

func (vo *Dept) SplitPageDeptList(pageIndex int64, pageSize int64) (interface{}, error) {
	var lists []Dept
	var total int64
	table := global.GDB.Table("dept")
	table = table.Select("  id,   name,   pid,   enabled,   create_time   ")
	if err := table.Count(&total).Error; err != nil {
		return lists, err
	}
	table = table.Offset((pageIndex - 1) * pageSize).Limit(pageSize)
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}

	m := make(map[string]interface{})
	m["lists"] = lists
	m["total"] = total
	return m, nil
}
